package com.example.demo.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.custom.AjaxResult;
import com.example.demo.entity.CarNumberCompany1;
import com.example.demo.entity.CarNumberCompany2;
import com.example.demo.form.CarNumberCompanyForm;
import com.example.demo.service.CarNumberCompanyService1;
import com.example.demo.service.CarNumberCompanyService2;

@RestController
@RequestMapping(value = "/CarNumberCompany")
public class CarNumberCompanyController1 {
	private DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
	
	@Autowired
	private CarNumberCompanyService1 CarNum1DAO;
	
	@Autowired
	private CarNumberCompanyService2 CarNum2DAO;
	
	@RequestMapping(value = "/save")
	private Object save(CarNumberCompanyForm Form) throws ParseException{
	  Integer carNum1Id = Form.getId();
	  CarNumberCompany1 CarNum1= new CarNumberCompany1();
	  CarNumberCompany1 carNum1= new CarNumberCompany1();
	  CarNumberCompany2 carNum2= new CarNumberCompany2();
	  CarNumberCompany2 CarNum2= new CarNumberCompany2();
	  Date d= new Date();
	  if(carNum1Id==null) {
		  CarNum1.setName(Form.getName());
		  carNum1 = CarNum1DAO.save(CarNum1);
	  }else {
		  carNum1 = CarNum1DAO.findById(carNum1Id);
		  carNum1.setName(Form.getName());
		  carNum1 = CarNum1DAO.save(carNum1);
		  Date d1 = dateFormat1.parse("1999-01-01");
		  List<CarNumberCompany2> list = CarNum2DAO.findByCarNumberCompany(carNum1);
		  for (CarNumberCompany2 carNum : list) {
				if(d1.compareTo(carNum.getBeginDate())==-1) {
					d1=carNum.getBeginDate();
					CarNum2=carNum;
				}
			}
		  CarNum2.setEndDate(d);
		  CarNum2DAO.save(CarNum2);	  	  
	  }
	  
		BeanUtils.copyProperties(Form, carNum2, "id","name");
		carNum2.setCarNumberCompany(carNum1);
		carNum2.setBeginDate(d);
		CarNum2DAO.save(carNum2);
		return new AjaxResult("数据保存成功");		
	}
	
	@RequestMapping(value = "/list")
	public Object list() {
		return new AjaxResult(CarNum1DAO.findAll());
	}
	
	@RequestMapping(value = "/findById")
	public Object findbyId(Integer id) throws ParseException {
		List<CarNumberCompany2> list = CarNum2DAO.findByCarNumberCompany(CarNum1DAO.findById(id));
		Date d = dateFormat1.parse("1999-01-01");
		CarNumberCompany2 n= new CarNumberCompany2();
		  for (CarNumberCompany2 carNum : list) {
				if(d.compareTo(carNum.getBeginDate())==-1) {
					d=carNum.getBeginDate();
					n=carNum;
				}
			}
		 return new AjaxResult(n);		
	}
	
}
